package com.xzz.mq.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.xzz.domain.CourseOrder;
import com.xzz.dto.Order2PayOrderParamDto;
import com.xzz.service.ICourseOrderService;
import com.xzz.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

//保存课程订单以及支付订单的事务消息
@Component
@RocketMQTransactionListener(txProducerGroup = "TxOrderGroupListener")
public class CourseOrderTransactionListener implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService courseOrderService;

    //执行本地事务 - 保存订单 ； message：消息内容 ; args :额外参数
    //1.在这里保存订单：需要订单数据(订单+订单明细)
    //2.需要把数据发送到MQ用作保存支付单
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object args) {

        try {
            AssertUtil.isNotNull(args,"订单数据为空");
            //课程订单
            CourseOrder courseOrder = (CourseOrder) args;
            //保存课程订单和明细
            courseOrderService.saveOrderAndItem(courseOrder);
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            e.printStackTrace();
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }

    //检查本地事务 - 检查订单是否超过
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        //支付单数据，也是要发给MQ的消息
        try {
            byte[] bytes = (byte[]) message.getPayload();
            String orderJSON = new String(bytes, StandardCharsets.UTF_8);
            Order2PayOrderParamDto paramDto = JSON.parseObject(orderJSON, Order2PayOrderParamDto.class);
            //根据订单号查询订单
            CourseOrder courseOrder = courseOrderService.selectByOrderNo(paramDto.getOrderNo());
            if(courseOrder != null){
                return RocketMQLocalTransactionState.COMMIT;
            }else {
                return RocketMQLocalTransactionState.ROLLBACK;
            }
        }catch (Exception e){
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}